import React, { Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Card, Form, Divider, Radio, Col, Row, DatePicker, message, Select } from 'antd';
import StandardTable from '@/components/StandardTable';
import Ellipsis from '@/components/Ellipsis';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import GmvSetForm from './component/GmvSetForm';
import OptLogView from '../component/OptLogView';

import styles from '../../styles/Manage.less';

const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// 2天后的日期
const lateOf2Day = moment(new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 2));

@Form.create()
@connect(({ gmvConf, loading }) => ({
  gmvConf,
  loading: loading.models.gmvConf,
}))
class GmvManage extends React.Component {
  state = {
    lv1ClassifyType: 0, // 默认全部
    forecastDate: lateOf2Day, // 被预测时间
    forecastDateString: lateOf2Day.format('YYYY-MM-DD'),
    modalVisible: false,
    optLogVisible: false, // 操作日志
    recordValue: {},
    progressStatus: -1, // 处理状态
    selectedCityList: [],
    selectedWarehouseList: [],
    cityList: [],
    warehouseList: [],
  };

  // 表格字段
  columns = [
    {
      title: '日期',
      width: 160,
      fixed: 'left',
      align: 'center',
      render: (text, record) => (
        <span>
          {record.forecastDate}({record.dayOfWeek})
        </span>
      ),
    },
    { title: '城市类型', width: 120, dataIndex: 'cityType' },
    { title: '城市', width: 120, dataIndex: 'cityName' },
    { title: '仓库', width: 120, dataIndex: 'warehouseName' },
    { title: '1级分类', width: 120, dataIndex: 'lv1ClassifyName' },
    {
      title: 'UV',
      dataIndex: 'uv',
      width: 100,
      render: text => <span style={{ color: 'blue' }}>{text}</span>,
    },
    {
      title: '转化率',
      dataIndex: 'conversionRate',
      width: 120,
      render: text => <span style={{ color: 'blue' }}>{text}</span>,
    },
    {
      title: '客单价',
      dataIndex: 'custPrice',
      width: 120,
      render: text => <span style={{ color: 'blue' }}>{text}元</span>,
    },
    { title: 'GMV', width: 120, dataIndex: 'gmv' },
    {
      title: '备注',
      dataIndex: 'comments',
      render: text => (
        <div style={{ width: 120 }}>
          <Ellipsis tooltip lines={1}>
            {text}
          </Ellipsis>
        </div>
      ),
    },
    { title: '最后操作人', width: 160, dataIndex: 'modifier' },
    {
      title: '最后修改时间',
      width: 160,
      dataIndex: 'modified',
      render: text => <span>{moment.unix(text).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      width: 120,
      align: 'center',
      fixed: 'right',
      dataIndex: 'option',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleOptLogModalVisible(true, record)}>日志</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.handleSearch();
    this.listCity();
    this.listWarehouse();
  }

  listCity = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastResult/listCity',
      callback: data => {
        this.setState({ cityList: data });
      },
    });
  };

  listWarehouse = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastResult/listWarehouse',
      callback: data => {
        this.setState({ warehouseList: data });
      },
    });
  };

  getForecastProgress = () => {
    const { dispatch } = this.props;
    const { forecastDateString, lv1ClassifyType } = this.state;
    dispatch({
      type: 'forecastResult/fetchForecastProgress',
      payload: {
        forecastDate: forecastDateString,
        lv1ClassifyType,
      },
      callback: data => {
        this.setState({
          progressStatus: data,
        });
      },
    });
  };

  // 修改
  handleModalVisible = (flag, record) => {
    const { progressStatus, lv1ClassifyType } = this.state;
    if (lv1ClassifyType === 0) {
      message.warn('请选择一级类目后再修改');
      return;
    }
    if (progressStatus <= 0) {
      this.setState({
        modalVisible: !!flag,
        recordValue: record || {},
      });
    } else {
      message.warn('当前状态不允许修改');
    }
  };

  // 操作日志
  handleOptLogModalVisible = (flag, record) => {
    this.setState({
      optLogVisible: !!flag,
      recordValue: record || {},
    });
  };

  getQueryParams = () => {
    const {
      lv1ClassifyType,
      forecastDateString,
      selectedCityList,
      selectedWarehouseList,
    } = this.state;
    const params = {};
    if (lv1ClassifyType !== 0) {
      params.lv1ClassifyType = lv1ClassifyType;
    }
    if (forecastDateString) {
      params.forecastDate = forecastDateString;
    }
    params.cityIdList = selectedCityList;
    params.warehouseIdList = selectedWarehouseList;
    return params;
  };

  // 查询操作
  handleSearch = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParams();
    dispatch({
      type: 'gmvConf/fetch',
      payload: {
        params,
      },
      callback: () => {
        this.getForecastProgress();
      },
    });
  };

  handleEditGmv = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'gmvConf/update',
      payload: fields,
      callback: () => {
        message.success('修改成功');
        this.handleModalVisible();
        // 重载数据
        this.handleSearch();
      },
    });
  };

  // 分页、过滤、排序处理
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const queryParams = this.getQueryParams();

    const params = {
      ...formValues,
      ...filters,
      ...queryParams,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'gmvConf/fetch',
      payload: {
        params,
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },
    });
  };

  formatValue = (value, defaultValue = '-') => {
    if (value === null || value === undefined) {
      return defaultValue;
    }
    return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  };

  renderTableTitle = () => {
    const {
      gmvConf: {
        data: { gmv },
      },
    } = this.props;
    return (
      <span style={{ color: 'red', fontWeight: 'bold' }}>
        合计： GMV:<span>{this.formatValue(gmv, '-')}</span>
      </span>
    );
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      gmvConf: {
        data: { data },
      },
    } = this.props;
    const {
      lv1ClassifyType,
      forecastDate,
      modalVisible,
      optLogVisible,
      recordValue,
      selectedCityList,
      cityList,
      selectedWarehouseList,
      warehouseList,
    } = this.state;

    let totalWidth = 0;
    this.columns.forEach(col => {
      const { width } = col;
      if (width) {
        totalWidth += width;
      }
    });

    return (
      <PageHeaderWrapper title="GMV设置" content="注意：GMV必须在出数据当日12：00前完成修改！">
        <Card bordered={false}>
          <div className={styles.Manage}>
            <div className={styles.ManageForm}>
              <Form layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={6} sm={24}>
                    <FormItem key="forecastDate" label="被预测日期">
                      {getFieldDecorator('forecastDate', {
                        initialValue: forecastDate,
                      })(
                        <DatePicker
                          onChange={(date, dateString) => {
                            this.setState(
                              {
                                forecastDate: date,
                                forecastDateString: dateString,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                          placeholder="选择日期"
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="lv1ClassifyType" label="一级类目">
                      {getFieldDecorator('lv1ClassifyType', {
                        initialValue: lv1ClassifyType,
                      })(
                        <Radio.Group
                          onChange={e => {
                            this.setState(
                              {
                                lv1ClassifyType: e.target.value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          <Radio.Button value={0}>全部</Radio.Button>
                          <Radio.Button value={1}>水果</Radio.Button>
                          <Radio.Button value={2}>蔬菜</Radio.Button>
                        </Radio.Group>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={10} sm={24}>
                    <FormItem key="cityId" label="城市">
                      {getFieldDecorator('cityIdList', {
                        initialValue: selectedCityList,
                      })(
                        <Select
                          placeholder="选择城市(支持多选)"
                          allowClear
                          mode="multiple"
                          onChange={e => {
                            this.setState(
                              {
                                selectedCityList: e,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          {cityList.map(item => (
                            <Select.Option value={item.id}>{item.name}</Select.Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col md={10} sm={24}>
                    <FormItem key="warehouse" label="仓库">
                      {getFieldDecorator('warehouseList', {
                        initialValue: selectedWarehouseList,
                      })(
                        <Select
                          placeholder="选择仓库(支持多选)"
                          allowClear
                          mode="multiple"
                          onChange={e => {
                            this.setState(
                              {
                                selectedWarehouseList: e,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          {warehouseList.map(item => (
                            <Select.Option value={item.id}>{item.name}</Select.Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
            <Divider type="horizontal" />
            <StandardTable
              loading={loading}
              data={data}
              scroll={{ x: totalWidth }}
              columns={this.columns}
              rowKey={record => record.id}
              title={this.renderTableTitle}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {modalVisible && (
          <GmvSetForm
            values={recordValue}
            modalVisible={modalVisible}
            handleOpt={this.handleEditGmv}
            handleModalVisible={this.handleModalVisible}
          />
        )}
        {optLogVisible && (
          <OptLogView
            values={recordValue}
            modalVisible={optLogVisible}
            viewType="gmv"
            handleModalVisible={this.handleOptLogModalVisible}
          />
        )}
      </PageHeaderWrapper>
    );
  }
}

export default GmvManage;
